package com.utils;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.model.StageInfo;


public class Downloader {

	private String url;
	
	
	public boolean ifConfigure(String url)
	{
		DefaultHttpClient httpClient = new DefaultHttpClient();
		URI uri;
		try {
			uri = new URI(url);
			HttpGet httpGet = new HttpGet(uri);
			HttpResponse response = httpClient.execute(httpGet);
			int returnCode = response.getStatusLine().getStatusCode();
			if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
				System.out
						.println("The Get method is not implemented by this URI");
		         return false;
			} else {
				System.out.println("Method Get Sucessfully!");;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		
		return false;
	}
	
	public int config(String URL, String login, String filePath,String fileName){
		DefaultHttpClient httpClient = new DefaultHttpClient();
		FileUtils fileUtils=new FileUtils();
		InputStream inputStream=null;

		String url=URL+"/stage/login";
		URI uri;
		try {
			uri = new URI(url);
			HttpPost post = new HttpPost(uri);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("security_key", login));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps,
					HTTP.UTF_8);
			post.setEntity(entity);			
			HttpResponse response = httpClient.execute(post);
			System.out.println("executing request " + post.getRequestLine());
			inputStream=response.getEntity().getContent();
			String line=null;
			if(inputStream!=null){
				StringBuffer sb=new StringBuffer();
				BufferedReader buffer=new BufferedReader(new InputStreamReader(inputStream));
				while((line=buffer.readLine())!=null){
					sb.append(line);					
				}
				
				System.out.println("connecting server : "+sb.toString());
				if(sb!=null&&sb.toString()==""){
					String str="server::"+URL+"\n"+"user::"+login;
					if(fileUtils.writeToSDFromString(filePath, fileName, str)!=null){
						return 0;
					}else{
						return -1;
					}
				}else{
					System.out.println("Connecting server failed");
					return -1;
				}
				
			}else{
				System.out.println("connecting server failed");
				return -1;
			}
						
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
			
		}
		
		
	}

	public int login(String url, String login, String password, String filePath, String fileName) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		FileUtils fileUtils=new FileUtils();
		InputStream inputStream=null;

		URI uri;
		try {
			uri = new URI(url);
			HttpPost post = new HttpPost(uri);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("LoginForm[username]", login));
			nvps.add(new BasicNameValuePair("LoginForm[password]", password));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps,
					HTTP.UTF_8);
			post.setEntity(entity);			
			HttpResponse response = httpClient.execute(post);
			System.out.println("executing request " + post.getRequestLine());
			inputStream=response.getEntity().getContent();
			File PDFFile = fileUtils.writeToSDFromInput(filePath, fileName,inputStream);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
			
		}
		
		return 0;

	}

	public int uploadPDF(String filePath, String fileName, String url,
			String nameAttr ,String securityKey) {

		DefaultHttpClient httpClient = new DefaultHttpClient();
		URI uri;
		FileUtils fileUtils = new FileUtils();

		if (!fileUtils.isFileExist(filePath + fileName)) {
			System.out.println("file does not exsit: " + filePath + fileName);
			return 1;
		}
		try {
			uri = new URI(url);
			HttpPost post = new HttpPost(uri);
			MultipartEntity form = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			httpClient.getParams().setBooleanParameter(
					"http.protocol.expect-continue", false);
			File uploadPDF = fileUtils.createSDFile(filePath + fileName);
			FileBody fileBody = new FileBody(uploadPDF);
			form.addPart(nameAttr, new StringBody(""));
			form.addPart(nameAttr, fileBody);
			form.addPart("security_key", new StringBody(securityKey));
			post.setEntity(form);
			httpClient.execute(post);
			System.out.println("executing request " + post.getRequestLine());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		}

		return 0;
	}

	// public int UploadPDF(String urlStr, String filePath, String fileName ){

	//
	// }
	// downloadPDF from the Server,
	// 1 means file exists; -1 means errors found during downloading; 0 means
	// download successfully
	public int downloadPDF(String urlStr, String filePath, String fileName) {
		InputStream inputStream = null;
		try {
			FileUtils fileUtils = new FileUtils();
			if (fileUtils.isFileExist(filePath + fileName)) {
				System.out.println("The file exists.....");
				return 1;
			} else {
				inputStream = getInputStreamFromURL(urlStr);
				File PDFFile = fileUtils.writeToSDFromInput(filePath, fileName,
						inputStream);
				if (PDFFile == null) {
					return -1;
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return -1;
		} finally {
			try {
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println("File Created....");
		return 0;
	}

	private InputStream getInputStreamFromURL(String urlStr)
			throws MalformedURLException, IOException {
		URL url=new URL(urlStr);
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		InputStream inputStream = urlConn.getInputStream();
		return inputStream;
	}

	
	public InputStream postProf(String fileName, String url, String login,
			String loginValue,String promo) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		URI uri;
		InputStream inputData = null;
		try {
			uri = new URI(url + "?" + login + "=" + loginValue+"&promo="+promo);
			System.out.println(uri.toString());
			HttpGet httpGet = new HttpGet(uri);
			// httpClient.getParams().setParameter("login_ece", "admin1");
			// post.getParams().setParameter("login_ece", "admin1");
			
			// List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			// nvps.add(new BasicNameValuePair("login_ece", "admin1"));
			// post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

			// Map<String, String> data = new HashMap<String, String>();
			// data.put("login_ece", "admin1");
			// postData.put("salary", "100");

			// ArrayList<BasicNameValuePair> postData = new
			// ArrayList<BasicNameValuePair>();
			// for (Map.Entry<String, String> m : data.entrySet()) {
			// postData.add(new BasicNameValuePair(m.getKey(), m.getValue()));
			// }

			// UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData,
			// HTTP.UTF_8);
			// httpPost.setEntity(entity);

			HttpResponse response = httpClient.execute(httpGet);
			int returnCode = response.getStatusLine().getStatusCode();
			if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
				System.out
						.println("The Get method is not implemented by this URI");

			} else {
				System.out.println("Method Get Sucessfully!");
				inputData = response.getEntity().getContent();

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return inputData;
	}

	public List<StageInfo> runJSONParser(InputStream data) {

		List<StageInfo> stageInfoList = null;
		try {
			System.out.println("Json Parser Started...");
			Gson gson = new Gson();
			Reader json = new InputStreamReader(data);
			System.out.println(json.toString());
			Type collectionType = new TypeToken<List<StageInfo>>() {
			}.getType();
			stageInfoList = gson.fromJson(json, collectionType);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return stageInfoList;
	}


}
